import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class FutureBuilderTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _FutureBuilderTestState();
  }
}

class _FutureBuilderTestState extends State<FutureBuilderTest> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("FutureBuilder"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FutureBuilder(
              future: netWorkData(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasError) {
                    return Text("请求出错");
                  } else {
                    return Text(snapshot.data.toString());
                  }
                } else {
                  return CircularProgressIndicator();
                }
              },
            ),
            StreamBuilder(
              stream: streamCounter(),
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Text("Error: ${snapshot.error}");
                } else if (snapshot.connectionState == ConnectionState.done) {
                  return Text("straem已关闭");
                } else if (snapshot.connectionState == ConnectionState.active) {
                  return Text("active:${snapshot.data}");
                } else {
                  return Text("等待数据");
                }
              },
            ),
          ],
        )
      ),
    );
  }

  Future<String> netWorkData() async {
    return Future.delayed(Duration(seconds: 3), () {
      return "互联网数据";
    });
  }

  Stream<int> streamCounter() {
    return Stream.periodic(Duration(milliseconds: 200),(i) => i);
  }
}
